#include <stdlib.h>
#include <assert.h>
#include "inputwidget.h"
#include "characterdata.h"

//const char *DATA_FILE = "strokes.dat";

InputWidget::InputWidget()
{
    /*
    _data_file = DATA_FILE;
    if ((_data_fd = open(_data_file, O_RDONLY)) == -1) {
        perror("Failed to open data file!");
        assert(_data_fd != -1);
        exit(-1);
    }*/
    init_data();
}

InputWidget::~InputWidget()
{
    //close(_data_fd);
}

void InputWidget::MousePressed()
{
    this.requestFocus();
    this.previousPoint = this.inputCharacter.new WrittenPoint(e.getX(), e.getY());
}

//double MIN_STROKE_SEGMENT_LENGTH = 5.0;
void InputWidget::MouseMoved()
{
    WrittenCharacter.WrittenPoint nextPoint = this.inputCharacter.new WrittenPoint(e.getX(), e.getY());
		
		if(null != this.previousPoint && this.previousPoint.distance(nextPoint) >= MIN_STROKE_SEGMENT_LENGTH) {
			// If the mouse has not been dragged a minimal distance, then we ignore this event.
			
			if(null == this.currentStroke) {
				// If the current stroke is null, that means that the this is the second point of the stroke.
				// The first point is stored this.previousPoint.
				// Now that we know that there is a second point we can add both points to a newly initialized stroke.
				this.currentStroke = this.inputCharacter.new WrittenStroke();
				this.currentStroke.addPoint(this.previousPoint);
			}
			
			// Add the new point to the WrittenStroke, and cycle the previousPoint.
			this.currentStroke.addPoint(nextPoint);
			this.previousPoint = nextPoint;
			this.repaint();
		}
}

void InputWidget::MouseRelase()
{
    this.mouseDragged(e);	// do the same stuff we do when the mouse is dragged
	
		if(null != this.currentStroke) {
			// The current stroke will still be null if the mouse wasn't dragged far enough for a new stroke.
			
			// Add the new WrittenStroke to the WrittenCharacter, and reset input variables.
			this.inputCharacter.addStroke(this.currentStroke);
			this.previousPoint = null;
			this.currentStroke = null;
			this.repaint();
		}
		
		this.notifyStrokesListeners();
}

    
void InputWidget::clear()
{
    inputCharacter->clear();
	currentStroke = null;
}

//todo
void InputWidget::undo()
{
    List strokesList = this.inputCharacter.getStrokeList();
		if(strokesList.size() > 0) {
			strokesList.remove(strokesList.size() - 1);
		}
}

WrittenCharacter InputWidget::getCharacter()
{
    return inputCharacter;
}